package com.mk.controller;

import com.mk.entity.Cargo;
import com.mk.mapper.CargoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/cargo")
@RestController
public class CargoController {
    @Autowired
    CargoMapper cargoMapper;

    /**
     * pages
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping("/list/{index}/{size}")
    public Page<Cargo> queryList(@PathVariable("index")Integer pageIndex, @PathVariable("size") Integer pageSize){
        if(pageIndex==null)
            pageIndex = 0;
        if(pageSize==null)
            pageSize = 10;
        PageRequest pageRequest = PageRequest.of(pageIndex, pageSize);
        return cargoMapper.findAll(pageRequest);
    }

    /**
     * 删除
     * @param id
     */
    @DeleteMapping("/remove/{id}")
    public void removeCargo(@PathVariable("id")Integer id){
        cargoMapper.deleteById(id);
    }

    /**
     * 新增
     * @param cargo
     * @return
     */
    @PostMapping("/add")
    public String addCargo(@RequestBody Cargo cargo){
        Cargo c = cargoMapper.save(cargo);
        if(c!=null)
            return "success";
        return "error";
    }

    /**
     * 更新
     * @param cargo
     * @return
     */
    @PutMapping("/set")
    public String editCargo(@RequestBody Cargo cargo){
        Cargo c = cargoMapper.save(cargo);
        if(c!=null)
            return "success";
        return "error";
    }

    /**
     * 根据编号查询
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    public Cargo findById(@PathVariable("id") Integer id){
        Cargo cargo = cargoMapper.findById(id).get();
        return cargo;
    }

}
